<?php

namespace Anchu\Cockpit\Decorators\Actions;

use Anchu\Cockpit\Decorators\IDecorator;
use Lvzmen\Helper\iArrayHelper;

// 对地图进行信息统计
class GetMapSumWithFilterInBody extends Action
{
    /**
     * @var IDecorator
     */
    public $decorator;

    public function run($arguments): IDecorator
    {
        $townName = $arguments[0] ?? '';
        $townCode = $arguments[1] ?? '';
        $villageName = $arguments[2] ?? '';
        $villageCode = $arguments[3] ?? '';
        $sum = $arguments[4] ?? '';

        // 进行统计工作
        $data = $this->isTown()
            ?
            iArrayHelper::sum($this->decorator->data, [$townName => 'name', $townCode => 'code'], [$sum => 'value']) :
            iArrayHelper::sum($this->decorator->data, [$villageName => 'name', $villageCode => 'code'], [$sum => 'value']);

        // 去掉为null的统计结果
        $this->decorator->data = array_values(array_filter($data, function ($item) {
            return !is_null($item['name']);
        }));
        return $this->decorator;
    }

    private function isTown()
    {
        return request()->query('filter', '') == '';
    }
}
